﻿using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using TY.UC.Common.Extension;

namespace TY.UI.Mvc
{
    /// <summary>
    /// wap页面授权拦截
    /// </summary>
    public class WapAuthorityAttribute : ActionFilterAttribute
    {
        private static readonly string ErrorUrl = "ErrorUrl".GetStrValue();//错误地址
        private static readonly string AuthorUrl = "AuthorUrl".GetStrValue();//授权地址
        private static readonly string ReturnUrl = "ReturnUrl".GetStrValue();//授权成功回跳地址
        private readonly List<string> _list = new List<string> { "oauth", "logon", "error" };//免拦截的action名称

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (_list.Contains(filterContext.ActionDescriptor.ActionName.ToLower()))
                return; 
            var request = filterContext.HttpContext.Request;
            //浏览器判断,直接拦截非微信，非支付宝
            if (request.UserAgent != null)
            {
                var ua = request.UserAgent.ToLower();
                if (!ua.Contains("micromessenger") && !ua.Contains("alipay"))
                {
                    filterContext.Result = new RedirectResult(ErrorUrl);
                    return;
                }
            }

            //强制重新登录
            if (request.Url.ToString().Contains("&qrcode"))
            {
                //授权信息为空，跳转到授权页面
                filterContext.Result = new RedirectResult(string.Format("{0}?url={1}", AuthorUrl, HttpUtility.UrlEncode(ReturnUrl)));
            }

            //获取用户信息
            var uck = request.Cookies["oauth"];
            
            //url页面请求格式应该统一（如http://xxx.xxxx.xxx?param=jsonStr）
            //获取页面请求的参数，并写入cookie，以便授权完成后，再次跳转进来，参数不会丢失
            var param = request["param"];
            //请求参数写入cookie
            SetCookies("param", param);
            if (uck != null && !string.IsNullOrEmpty(uck.Value)) return;
            if (filterContext.HttpContext.Request.IsAjaxRequest())
                filterContext.Result = new HttpStatusCodeResult(401, "登录过期，请重新登录");
            else
            //授权信息为空，跳转到授权页面
            filterContext.Result = new RedirectResult(string.Format("{0}?url={1}", AuthorUrl, HttpUtility.UrlEncode(string.Format("{0}?uorg={1}",ReturnUrl, filterContext.HttpContext.Request.Url.ToString()))));
        }
        private void SetCookies(string name, string value)
        {
            //创建并命名新的 Cookie。
            var ck = new HttpCookie(name)
            {
                HttpOnly = false,
                Value = HttpUtility.UrlEncode(value)
            };
            // 对 URL 字符串进行编码。
            // 获取当前 HTTP 响应的 System.Web.HttpResponse 对象。
            HttpContext.Current.Response.Cookies.Remove(name);
            HttpContext.Current.Response.Cookies.Add(ck);
        }
    }
}